package com.bolovan.infovaluta.reader;

import java.io.IOException;
import java.math.BigDecimal;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.bolovan.infovaluta.bean.ExchangeRate;
import com.bolovan.infovaluta.bean.ExchangeRateEntry;
import com.bolovan.infovaluta.bean.ExchangeRateSeller;
import com.bolovan.infovaluta.util.RateConstants;
import com.bolovan.infovaluta.util.RateMaps;
import com.bolovan.infovaluta.util.RateUtil;
import com.google.gson.Gson;

public class BcrReader extends ExchangeReader {

	public BcrReader(ExchangeRateSeller seller) {
		super(seller);
	}

	@Override
	public void buildRateMap(ExchangeRate map) throws IOException {
		fetchBCR(map);
	}

	private void fetchBCR(ExchangeRate map) throws IOException {
		setParsingDate(RateMaps.date);
		Document doc = RateUtil.getDocument(ExchangeRateSeller.BCR.getUrl());
		Elements currencyDiv = doc.getElementsByAttribute("data-currency");
		Gson gson = new Gson();
		for (Element e : currencyDiv) {
			ExchangeRateEntry values = gson.fromJson(e.attr("data-values"), ExchangeRateEntry.class);
			String currency = e.attr("data-currency");
			BigDecimal bid = values.getBid();
			BigDecimal ask = values.getAsk();
			if (RateConstants.multiplierCurrencyes.contains(currency)) {
				bid = bid.multiply(new BigDecimal(100));
				ask = ask.multiply(new BigDecimal(100));
			}
			map.addToMap(new ExchangeRateEntry(e.attr("data-currency"), bid, ask));
		}

	}
}
